package com.tngames.angrytunisian.game.core.entity;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.World;

public abstract class DynamicPhysicsEntity extends Entity implements
		PhysicsEntity {

	private Body body;
	private float prevX, prevY, prevA;

	public DynamicPhysicsEntity(EntityEngine entityEngine,
			float px, float py, float pangle) {

		super(entityEngine, px, py, pangle);
		body = initPhysicsBody(entityEngine.getWorld(),
				entityEngine.getGroundBody(), x, y, angle);
		setPos(x, y);
		setAngle(angle);
		this.prevA = pangle;
		this.prevX = px;
		this.prevY = py;
	}

	protected abstract Body initPhysicsBody(World world, Body groundBody,
			float x, float y, float angle);

	@Override
	public void update(float alpha) {

		// interpolate based on previous state
		float x = (body.getPosition().x * alpha) + (prevX * (1f - alpha));
		float y = (body.getPosition().y * alpha) + (prevY * (1f - alpha));
		float a = (body.getAngle() * alpha) + (prevA * (1f - alpha));
		layer.setTranslation(x, y);
		layer.setRotation(a);

		prevX = body.getPosition().x;
		prevY = body.getPosition().y;
		prevA = body.getAngle();
	}

	@Override
	public void initPreLoad(EntityEngine entityEngine) {
		entityEngine.dynamicLayer.add(layer);
	}

	@Override
	public void initPostLoad(EntityEngine entityEngine) {

	}

	public void setLinearVelocity(float x, float y) {
		body.setLinearVelocity(new Vec2(x, y));
	}

	public void setAngularVelocity(float w) {
		body.setAngularVelocity(w);
	}

	@Override
	public void setPos(float x, float y) {
		super.setPos(x, y);
		body.setTransform(new Vec2(x, y), body.getAngle());
		prevX = x;
		prevY = y;
	}

	@Override
	public void setAngle(float angle) {
		super.setAngle(angle);
		body.setTransform(body.getPosition(), angle);
		prevA = angle;
	}

	@Override
	public Body getBody() {
		return body;
	}

}
